<template>
    
    <!-- 组件的模板 -->
    <div class="page">
        <form>
            <div class="item flex">
                <input v-on:input="veriryPhoneFormat" v-model="formData.phone" id="regiPhone" type="tel" maxlength="11" placeholder="手机号码" :value="formData.phone">
            </div>
            <div class="item flex">
                <input v-model="formData.vCode" id="regiVcode" type="tel" class="input-text" maxlength="6" placeholder="验证码（6位）" :value="formData.vCode">
                <span v-if="formData.phone.length == 11" class="get-code flex active" @click="getVCode" v-show="!isCounting" id="getvCode"><span v-if="spacewhite">&nbsp;&nbsp;&nbsp;&nbsp;</span>{{countingTxt}}</span>
                <span v-else class="get-code flex" :disabled="!vCodeActive"  v-show="!isCounting" id="getvCode"><span v-if="spacewhite">&nbsp;&nbsp;&nbsp;&nbsp;</span>{{countingTxt}}</span>
                <span v-else class="get-code flex" @click="getVCode"  v-show="isCounting" :disabled="isCounting">{{countingTxt2}}</span>
            </div>              
            <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_primary" @click="bindPhone" v-if = "formData.phone && formData.vCode">绑 定</a>            
            <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_disabled weui-btn_primary" v-else>绑 定</a>            
        </form>
        <div class="link">
            <a href="dmsaas://CodeIntroduce">收不到验证码</a>
        </div>
        
    </div>   
</template>

<script>
    let receiveImgcode = true
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import $ from 'zepto'
    import userCenterApi from 'clientApi/userCenterApi'
    import clientInfo from 'gapi/clientInfo'
    import safety from 'gapi/safety'
    import widget from 'gapi/widget.js'
    import * as util from 'js/util.js'
    import commonPage from 'clientApi/commonPage.js'
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */

    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        data: function(){
            return{
                formData: {},
                isCounting: false,
                countingTxt: '获取验证码',
                countingTxt2: '',
                spacewhite: false,
                thridloginData: {
                  open_id: '',
                  union_id: '',
                  nick_name: '',
                  avatar_url: ''
                },
                bindPhoneData: {}
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
                
                this.thridloginData.open_id = util.getUrddataString('open_id')
                this.thridloginData.union_id = util.getUrddataString('union_id')
                this.thridloginData.nick_name = util.getUrddataString('nick_name')
                this.thridloginData.avatar_url = util.getUrddataString('avatar_url')
                
            },
            /**
            * 监听验证手机格式, 激活手机验证码按钮
            **/
            veriryPhoneFormat () {
                const phone = this.formData.phone;
                const phoneIsValid = /^\d{11}$/.test(phone);
                this.vCodeActive = phoneIsValid ? true : false;
            },
            /**
            * 获取手机验证码
            **/
            getVCode (){    
              if(!receiveImgcode){
                  return
              }
              receiveImgcode = false
              if(this.isCounting){
                return
              }
              //防止双击事件
              setTimeout(function(){
                receiveImgcode = true
              }, 1000)
                

                this.vCodeActive = false
                                
                commonPage.loadPageStatus('loading')
                util.ajax({
                    url: '/user/sendcode',
                    type:'POST',
                    data: {
                            mobile: this.formData.phone,
                        },
                    success: (res) => {
                      // alert(JSON.stringify(res))
                        commonPage.loadPageStatus('loadSuccess')
                        if(res&&res.errno==0){
                          this.isCounting = true; //show countdown button
                          this.countDown(60); //counting down
                        }else if(res.errmsg){
                          widget.toast(res.errmsg)
                        }else{
                          widget.toast('数据获取失败')
                        }
                    },
                    error: (xhr, error) => {
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('服务器异常')
                    },
                    noNetwork: () => {
                        // 无网络的回调
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('网络连接失败，请检查网络,设置失败')
                    }
                })
            },
            /**
            * 倒计时
            **/
            countDown (seconds){
              this.isCounting = true
              this.countingTxt2 = ''
              let _seconds = seconds;
              let tId;
              receiveImgcode = false
              
              tId = setInterval(() => {
                if (_seconds == 0){
                  clearInterval(tId);
                  this.isCounting = false
                  this.countingTxt = ' 重新获取'
                  this.vCodeActive = true;
                  receiveImgcode = true
                  this.spacewhite = true
                }else{
                  _seconds--;
                  this.countingTxt2 = `${_seconds}秒后重发`
                }
              }, 1000)
            },
            /**
            * 获取图片验证码图片
            **/
            getCaptcha (){
                let apiUrl = ""//todo 
                let headers = {}
               clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + util.getApiPath() + '/ajax/encodedcode'
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'GET',
                          dataType: 'json',
                          data: {
                            platform: util.OS(),
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {
                            if(!!data && !!data.pic_code){
                              this.base64ImgData = data.pic_code
                        }else{
                            widget.toast('服务器异常');
                        }
                          },
                          error: (xhr, status) => {
                            // util.ajaxErrorFn(widget,xhr,status,true,UCApi);
                          }
                       })  
                      })
                      
                    })
                  } else {
                      widget.toast('网络连接失败，请检查网络');
                  }
                })
            },
            /**
            * 刷新图片验证码
            **/
            refreshImg (){
              this.getVCode()
            },
            /**
            * 提交图片验证码
            **/
            submitImgCode (){
              let apiUrl = ""
              let headers = {}
              this.invalidImgCode = false
              if(!this.imgCode){
                this.invalidImgCode = true
                this.imgCodeErrMsg = '请输入正确的图片验证码'
                return;
              }
                clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + util.getApiPath() + '/authCkCode'//todo:encapsule
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'POST',
                          dataType: 'json',
                          data: {
                            mobile: this.formData.phone,
                            platform: util.OS(),
                            code : imageCode,
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {//图片验证码
                            this.isCounting = true; 
                            this.countDown(60); 
                          },
                          error: (xhr, status) => {
                            if (status == 'timeout'){
                              widget.toast('网络请求超时');
                            }else{
                                  if(xhr.status==400){
                                    //xhr.responseText.code : -4 -> 图片验证码错误; -206: 一分钟内不能获取验证码  
                                    this.invalidImgCode = true
                                    this.imgCodeErrMsg = JSON.parse(xhr.responseText).message
                                  }else{
                                      widget.toast('服务器异常');
                                  }
                              }
                          }
                       })  
                      })
                      
                    })
                  } else {
                    widget.toast('网络连接失败，请检查网络');
                  }
                })
            },
            bindPhone (){
                let that = this
                // this.hasError = true;
                //表单校验 todo: migrate to vue-validator
                if (!that.formData.phone){
                    widget.toast('请输入手机号') 
                    return
                }else if (that.formData.phone.length != 11){
                    widget.toast('请输入正确的手机号')
                    return
                }else if (!that.formData.vCode){ 
                    widget.toast('验证码不能为空')
                    return                    
                }else if (!/^\d{6}$/.test(that.formData.vCode)){ //非6位数字 
                    widget.toast('验证码错误')
                    return                    
                } else {
                  userCenterApi.bindPhoneNum(that.formData.phone, that.formData.vCode, data => {

                  })
                  // commonPage.loadPageStatus('loading')
                  // util.ajax({
                  //     url: '/user/thirdlogin',
                  //     type:'POST',
                  //     data: {
                  //             type: "weixin",
                  //             open_id: that.thridloginData.open_id,
                  //             union_id: that.thridloginData.union_id,
                  //             nick_name: that.thridloginData.nick_name,
                  //             avatar_url: that.thridloginData.avatar_url,
                  //             mobile: that.formData.phone,
                  //             code: that.formData.vCode,
                  //         },
                  //     success: (res) => {
                  //         commonPage.loadPageStatus('loadSuccess')
                  //         if(res&&res.errno==0){
                  //           //调用客户端登陆Api
                  //           that.bindPhoneData = res.data
                  //           // alert(JSON.stringify(res))
                  //         userCenterApi.bindPhoneNumSuccess(that.bindPhoneData.doumi_user_id, that.bindPhoneData.baxian_user_id, that.bindPhoneData.mobile, that.bindPhoneData.real_name, data => {
                  //           commonPage.loadPageStatus('loadSuccess')
                  //           if(!!data){                   
                  //             console.log("errorMessage"+data.code);
                  //             if (data.code == -201) {
                  //               widget.toast(data.message);
                  //             }else if(data.code == -313) {
                  //               widget.toast('当前用户未注册，请直接注册');
                  //             }else if(data.code == -312) {
                  //               widget.toast('密码错误，请点忘记密码进行重置');
                  //             }else{
                  //               widget.toast(data.message);
                  //             }
                  //           }
                  //           // Native toast: 密码错误 or  未注册
                  //         })
                            
                  //         }else if(res.errmsg){
                  //               widget.toast(res.errmsg)
                  //         }else{
                  //             widget.toast('数据获取失败')
                  //         }
                  //     },
                  //     error: (xhr, error) => {
                  //         commonPage.loadPageStatus('loadSuccess')
                  //         widget.toast('服务器异常')
                  //     },
                  //     noNetwork: () => {
                  //         // 无网络的回调
                  //         commonPage.loadPageStatus('loadSuccess')
                  //         widget.toast('网络连接失败，请检查网络,设置失败')
                  //     }
                  // })
                    
              }
            }
        },
        created(){

            this.init();
            
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<!-- <style src="static/css/global.css"></style> -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/global.css"></style>
<style src="../../static/css/login.css"></style>
<style src="../../static/css/form.css"></style>
<style src="../../static/css/account.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/login-register.css"></style>
<style>
  body{
    background: #fff!important;
  }
  .input-text{
    text-align: left!important;
  }
  ::-webkit-input-placeholder {
    color: #bbb!important;
  }
  .dialog__btn_primary {
    color: black!important;
  }

</style>


